import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { debounceTime, switchMap } from 'rxjs/operators';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { CenterService } from '@core/routes-services/center.service';
import { Observable } from 'rxjs/Observable';
import { OtcCustomerService } from '@core/routes-services/otc-customer.service';

@Component({
  selector: 'app-otc-center-form',
  templateUrl: './otc-center-form.component.html',
})
export class OtcCenterFormComponent implements OnInit {
  @Input() entity: any = {};
  @Input() isModel: boolean = true;
  validateForm: FormGroup;
  isLoading: boolean = false;
  @Output() finish = new EventEmitter();


  loadingOption: boolean = false;
  searchChange$ = new BehaviorSubject('');
  customerList: any [] = [];

  constructor(private fb: FormBuilder,
              private centerService: CenterService,
              private otcCustomerService: OtcCustomerService,
              public message: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(30)]],
      sortNum: [this.entity.sortNum, [Validators.required]],
      customerId: [this.entity.customerId, []],
    });
    this.initSearchChange();
  }

  initSearchChange() {
    const searchFanOptions = (name: string) => this.otcCustomerService.centerPagination(name).then((res) => {
      if (res.status.toString().startsWith('20')) {
        return res.data.content;
      } else {
        this.message.warning(res.message);
        return [];
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
      return [];
    });
    const optionList$: Observable<string[]> = this.searchChange$.asObservable().pipe(debounceTime(500)).pipe(switchMap(searchFanOptions));
    optionList$.subscribe(data => {
      // console.log(data);
      this.customerList = data;
      if (this.entity.customerId && this.customerList.findIndex(c => c.id == this.entity.customerId) == -1) {
        this.customerList.push({ id: this.entity.customerId, name: this.entity.centerUser.name });
      }
      this.loadingOption = false;
    });
  }

  onSearch(value: string): void {
    this.loadingOption = true;
    this.searchChange$.next(value);
  }

  submitForm(): void {
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      this.isLoading = true;
      this.centerService.saveOrUpdateEntity(this.entity.id, this.validateForm.value).then((res) => {
        console.log(res)
        if (res.status.toString().startsWith('20')) {
          this.finish.emit(res.data);
        } else {
          this.message.warning(res.message);
        }
        this.isLoading = false;
      }, error => {
        this.message.error(error.message ? error.message : error.error);
        this.isLoading = false;
      });
    }
  }

  close() {
    this.finish.emit(false);
  }
}
